package com.example.myapplication.common

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager


abstract class AbstractFragment : Fragment() {

    protected var contentView: View? = null
    protected var mIsFirstInitData = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        initArgs(arguments)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (contentView == null) {
            val inflate = inflater.inflate(getContentLayoutId(), container, false)
            initView(inflate)
            contentView = inflate
        } else {
            val parent = contentView!!.parent
            if (parent != null && parent is ViewGroup) {
                parent.removeView(contentView)
            }
        }
        return contentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!mIsFirstInitData) {
            mIsFirstInitData = true
            onFirstInit()
        }
        initData()
    }

    abstract fun getContentLayoutId(): Int

    protected open fun initArgs(savedInstanceState: Bundle?) {}

    protected open fun initView(contentView: View) {}

    protected open fun initData() {}

    /**
     * 当首次初始化数据的时候会调用的方法
     */
    protected open fun onFirstInit() {

    }

    protected open fun reportException(ex: Exception?) {
        Log.e("FragmentException", "reportException --> $ex")
    }

    protected open fun backFragment() {
        this.fragmentManager?.popBackStack()
    }

    fun onBackPressed(): Boolean{
        return false
    }

    open fun onMoreItemSelected(value: String): Boolean {
        return true
    }

    fun loadFragment(
        fragmentLayout:Int,
        fragment: Fragment,
        addToBackStack: Boolean
    ) {
        val fragmentManager = childFragmentManager
        val fragmentTransaction =
            fragmentManager.beginTransaction()
        val fragmentById =
            fragmentManager.findFragmentById(fragmentLayout)
        if (fragmentById == null) {
            fragmentTransaction.add(fragmentLayout, fragment, fragment.javaClass.name)
        } else {
            fragmentTransaction.replace(fragmentLayout, fragment, fragment.javaClass.name)
        }
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(fragment.javaClass.name)
        }
        fragmentTransaction.commit()
    }
}